// 客户模糊查询
import React from 'react';
import { Select, Spin } from 'antd';
import HOCSelect from '@/components/AntDesign/Select';
import { getContList } from '@/services/api';
import PropTypes from 'prop-types';
import Debounce from 'lodash-decorators/debounce';

const { Option } = Select;

class Contract extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      contList: [],
      loading: false,
    };
  }

  // 在这里先获取上级如果有传过来value先去获取一下数据，如果没有传则不用
  async componentDidMount() {
    const { value } = this.props;
    const queryVal = value?.title;
    if (!queryVal) {
      return false;
    }
    this.getContList(queryVal);
  }

  /**
   *模糊查询合同
   * @param {string} value 模糊查询所需值
   */
  @Debounce(1000)
  async getContList(value) {
    if (value.trim().length) {
      const { params } = this.props;
      this.setState({ loading: true });
      try {
        const response = await getContList({ contName: value.trim(), ...params });
        this.setState({
          contList: Array.isArray(response.data) ? response.data : [],
          loading: false,
        });
      } catch (e) {
        console.error(e);
      } finally {
        this.setState({ loading: false });
      }
    }
  }

  render() {
    const { getData, value, labelInValue, ...rest } = this.props;
    const { loading, contList } = this.state;
    return (
      <HOCSelect
        placeholder="请输入关键字检索"
        {...rest}
        showSearch
        labelInValue={labelInValue}
        value={labelInValue ? value : value?.title}
        optionFilterProp="children"
        showArrow={false}
        onSearch={val => this.getContList(val)}
        onSelect={(selectValue, options) => getData(selectValue, options)}
        notFoundContent={loading ? <Spin size="small" /> : '暂无数据'}
      >
        {contList.map(item => (
          <Option key={item.contId} title={item.contName}>
            {item.contName}
          </Option>
        ))}
      </HOCSelect>
    );
  }
}
Contract.defaultProps = {
  getData: () => {},
  params: {},
};
Contract.propTypes = {
  getData: PropTypes.func,
  params: PropTypes.object,
};
export default Contract;
